/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PublicHolidayDialog.java
 *
 * Created on 14-Apr-2011, 22:30:16
 */

package TimeRecording.forms;

import TimeRecording.TimeRecordingView;
import TimeRecording.tables.PublicHoliday;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.swing.JOptionPane;
import org.jdesktop.application.Action;

/**
 *
 * @author david
 */
public class PublicHolidayDialog extends javax.swing.JDialog {

    private final static String GET_HOLIDAYS = "PublicHoliday.findAll";

    private final static Logger LOGGER = Logger.getLogger(
            PublicHolidayDialog.class.getName());

    // <editor-fold defaultstate="collapsed" desc="selectedholiday + Getter & Setter">
    private PublicHoliday selectedHoliday = null;

    public PublicHoliday getSelectedHoliday() {
        return selectedHoliday;
    }

    public void setSelectedHoliday(PublicHoliday selectedHoliday) {
        PublicHoliday oldSelectedHoliday = this.selectedHoliday;
        this.selectedHoliday = selectedHoliday;
        firePropertyChange("selectedHoliday", oldSelectedHoliday, selectedHoliday);
        setHolidaySelected(selectedHoliday != null);
    } // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="holidaySelected + Getter & Setter">
    private boolean holidaySelected = false;

    public boolean getHolidaySelected() {
        return holidaySelected;
    }

    public void setHolidaySelected(boolean holidaySelected) {
        boolean oldHolidaySelected = this.holidaySelected;
        this.holidaySelected = holidaySelected;
        firePropertyChange("holidaySelected", oldHolidaySelected, holidaySelected);
    } // </editor-fold>

    public EntityManager getEntityManager() {
        return entityManager;
    }

    /** Creates new form PublicHolidayDialog */
    public PublicHolidayDialog(TimeRecordingView parent) {
        super(parent.getFrame(), true);
        myParent = parent;
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = myParent.getEntityManager();
        query = entityManager.createNamedQuery(GET_HOLIDAYS);
        holidayList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
        holidaysPanel = new javax.swing.JScrollPane();
        holidayTable = new javax.swing.JTable();
        buttonPanel = new javax.swing.JPanel();
        newButton = new javax.swing.JButton();
        editButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();
        grantButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(TimeRecording.TimeRecordingApp.class).getContext().getResourceMap(PublicHolidayDialog.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N
        getContentPane().setLayout(new java.awt.GridBagLayout());

        holidaysPanel.setName("holidaysPanel"); // NOI18N

        holidayTable.setName("holidayTable"); // NOI18N

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, holidayList, holidayTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${holidayId}"));
        columnBinding.setColumnName("Holiday Id");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${dateOfHoliday}"));
        columnBinding.setColumnName("Date Of Holiday");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${description}"));
        columnBinding.setColumnName("Description");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${selectedHoliday}"), holidayTable, org.jdesktop.beansbinding.BeanProperty.create("selectedElement"));
        bindingGroup.addBinding(binding);

        holidaysPanel.setViewportView(holidayTable);
        holidayTable.getColumnModel().getColumn(0).setMinWidth(50);
        holidayTable.getColumnModel().getColumn(0).setPreferredWidth(50);
        holidayTable.getColumnModel().getColumn(0).setMaxWidth(50);
        holidayTable.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("holidayTable.columnModel.title1")); // NOI18N
        holidayTable.getColumnModel().getColumn(1).setMinWidth(100);
        holidayTable.getColumnModel().getColumn(1).setPreferredWidth(100);
        holidayTable.getColumnModel().getColumn(1).setMaxWidth(100);
        holidayTable.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("holidayTable.columnModel.title0")); // NOI18N
        holidayTable.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("holidayTable.columnModel.title2")); // NOI18N

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(8, 8, 0, 8);
        getContentPane().add(holidaysPanel, gridBagConstraints);

        buttonPanel.setName("buttonPanel"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(TimeRecording.TimeRecordingApp.class).getContext().getActionMap(PublicHolidayDialog.class, this);
        newButton.setAction(actionMap.get("newHoliday")); // NOI18N
        newButton.setText(resourceMap.getString("newButton.text")); // NOI18N
        newButton.setName("newButton"); // NOI18N
        buttonPanel.add(newButton);

        editButton.setAction(actionMap.get("editHoliday")); // NOI18N
        editButton.setText(resourceMap.getString("editButton.text")); // NOI18N
        editButton.setName("editButton"); // NOI18N
        buttonPanel.add(editButton);

        deleteButton.setAction(actionMap.get("deleteHoliday")); // NOI18N
        deleteButton.setText(resourceMap.getString("deleteButton.text")); // NOI18N
        deleteButton.setName("deleteButton"); // NOI18N
        buttonPanel.add(deleteButton);

        grantButton.setAction(actionMap.get("grantHoliday")); // NOI18N
        grantButton.setText(resourceMap.getString("grantButton.text")); // NOI18N
        grantButton.setName("grantButton"); // NOI18N
        buttonPanel.add(grantButton);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridheight = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        getContentPane().add(buttonPanel, gridBagConstraints);

        bindingGroup.bind();

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-387)/2, (screenSize.height-325)/2, 387, 325);
    }// </editor-fold>//GEN-END:initComponents

    @SuppressWarnings("unchecked")
    @Action
    public void newHoliday() {

        // Create a new badge and allow user to edit it
        PublicHoliday newHoliday = new PublicHoliday();
        PublicHolidayEditor editor = new PublicHolidayEditor(this);
        editor.setPublicHoliday(newHoliday);
        editor.setVisible(true);

        // If user has bottled the editor then just ditch the new badge
        if (!editor.getSaved()) {
            return;
        }

        // Persist the new badge
        try {
            entityManager.getTransaction().begin();
            entityManager.persist(newHoliday);
            entityManager.getTransaction().commit();

        } catch (RuntimeException e) {
            LOGGER.log(Level.SEVERE, "Error creating public holiday", e);
            if (entityManager.getTransaction().isActive()) {
                entityManager.getTransaction().rollback();
            }
            ErrorDialog.showError(this, e);
        }

        // Refresh the list
        holidayList.clear();
        holidayList.addAll((List<PublicHoliday>)query.getResultList());

        // Select the newly created row
        for (int row = 0; row < holidayTable.getRowCount(); row++) {
            if (holidayTable.getValueAt(row, 0).
                    equals(newHoliday.getHolidayId())) {
                holidayTable.scrollRectToVisible(
                        holidayTable.getCellRect(row, 0, true));
                holidayTable.setRowSelectionInterval(row, row);
            }
        }
    }

    @Action(enabledProperty = "holidaySelected")
    public void editHoliday() {

        // Create a new badge and allow user to edit it
        PublicHolidayEditor editor = new PublicHolidayEditor(this);
        editor.setPublicHoliday(getSelectedHoliday());
        editor.setVisible(true);

        // If user has bottled the editor then just ditch the new badge
        if (!editor.getSaved()) {
            entityManager.refresh(getSelectedHoliday());
            return;
        }

        // Persist the new badge
        try {
            entityManager.getTransaction().begin();
            entityManager.merge(getSelectedHoliday());
            entityManager.getTransaction().commit();

        } catch (RuntimeException e) {
            LOGGER.log(Level.SEVERE, "Error editing public holiday", e);
            if (entityManager.getTransaction().isActive()) {
                entityManager.getTransaction().rollback();
            }
            ErrorDialog.showError(this, e);
        }
    }

    @SuppressWarnings("unchecked")
    @Action(enabledProperty = "holidaySelected")
    public void deleteHoliday() {

        if (JOptionPane.showConfirmDialog(this,
                "Are you sure you wish to delete the holiday",
                "Delete Public Holiday",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.WARNING_MESSAGE) != JOptionPane.YES_OPTION) {
            return;
        }

        try {
            entityManager.getTransaction().begin();
            entityManager.remove(selectedHoliday);
            entityManager.getTransaction().commit();

            // Refresh the list
            holidayList.clear();
            holidayList.addAll((List<PublicHoliday>)query.getResultList());

        } catch (RuntimeException e) {
            LOGGER.log(Level.SEVERE, "Error deleting public holiday", e);
            if (entityManager.getTransaction().isActive()) {
                entityManager.getTransaction().rollback();
            }
            ErrorDialog.showError(this, e);
        }
    }

    @SuppressWarnings("unchecked")
    @Action(enabledProperty = "holidaySelected")
    public void grantHoliday() {
        // Create a new badge and allow user to edit it
        PublicHolidayGrantDialog dialog = new PublicHolidayGrantDialog(this);
        dialog.setPublicHoliday(getSelectedHoliday());
        dialog.setVisible(true);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel buttonPanel;
    private javax.swing.JButton deleteButton;
    private javax.swing.JButton editButton;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JButton grantButton;
    private java.util.List<TimeRecording.tables.PublicHoliday> holidayList;
    private javax.swing.JTable holidayTable;
    private javax.swing.JScrollPane holidaysPanel;
    private javax.swing.JButton newButton;
    private javax.persistence.Query query;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    private TimeRecordingView myParent;
}
